package com.byzk.p2p.front.filter;

import java.io.IOException;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;

import com.byzk.p2p.admin.user.dto.User;

public class SessionFilter extends HttpServlet implements Filter{

	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	
	private FilterConfig filterConfig;

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		this.filterConfig = filterConfig;
	}

	@Override
	protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		super.doPost(req, resp);
	}
	
	@Override
	protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
		super.doGet(req, resp);
	}
	
	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		HttpServletRequest req = (HttpServletRequest)request ;
		HttpServletResponse res = (HttpServletResponse)response;
		User user = (User)req.getSession().getAttribute("_user");
		if(user == null){
			 req.setAttribute("page", "login.ftl"); 
	         ServletContext ctx = filterConfig.getServletContext();
	         ctx.getRequestDispatcher("/login").forward(req, res); 
		}else{
			req.getSession().setAttribute("_user", user); //重新设置session 
			if(StringUtils.isBlank(user.getPhone())){
				 req.setAttribute("page", "binding.ftl"); 
		         ServletContext ctx = filterConfig.getServletContext();
		         ctx.getRequestDispatcher("/binding/phone").forward(req, res); 				
			}else{
				if(req.getRequestURI().indexOf("/thirdRegister")==-1){
					if("N".equals(user.getFuionAccount())){
						 req.setAttribute("page", "/account/register.ftl"); 
				         ServletContext ctx = filterConfig.getServletContext();
				         ctx.getRequestDispatcher("/account/register").forward(req, res); 				
					}else{
						chain.doFilter(req, res);//用户通过验证
					}
				}else{
					
					chain.doFilter(req, res);//用户通过验证
				}				
			}
		}	
	}
	
	@Override
	public void destroy() {
		filterConfig = null;
	}

}
